﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DTOTemplatedGenerator.Models;
using DTOTemplatedGenerator.Utils;
using DTOTemplatedGenerator.ViewModels;
using Microsoft.Win32;
using Newtonsoft.Json;

namespace DTOTemplatedGenerator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
		ViewModel _model;

        private int rowIndex = -1;
        private DragAndDropDataGridRows _dndPropsGrid;
        private DragAndDropDataGridRows _dndTemplatesGrid;
        private DragAndDropDataGridRows _dndGenTemplatesGrid;
        private DragAndDropDataGridRows _dndTypesTransGrid;
        public MainWindow()
        {
            InitializeComponent();
            
            _dndPropsGrid = new DragAndDropDataGridRows(dataGridProps);
            _dndTemplatesGrid = new DragAndDropDataGridRows(dataGridTemplates);
            _dndGenTemplatesGrid = new DragAndDropDataGridRows(dataGridGeneralTemplates);
            _dndTypesTransGrid = new DragAndDropDataGridRows(dataGridTypes);
        }

		protected override void OnActivated(EventArgs e)
		{
			_model = DataContext as ViewModel;
			_model.GetSelectedProps = () =>
                                          {
                                              var selected = dataGridProps.SelectedItems.OfType<PropertyModel>().ToList();
                                              selected.Sort((pm1, pm2) => _model.Props.IndexOf(pm1).CompareTo(_model.Props.IndexOf(pm2)));
                                              return selected;
                                          };
			base.OnActivated(e);
		}

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
			_model.SaveData();
        }

		private void onSelectDeselect(object sender, RoutedEventArgs e)
		{
			dataGridProps.Focus();
			if (dataGridProps.Items.Count <= dataGridProps.SelectedItems.Count)
				dataGridProps.SelectedItems.Clear();
			else dataGridProps.SelectAll();
		}

        private void onSaveTemplates(object sender, RoutedEventArgs e)
        {
            _model.SaveTemplates();
        }

        private void onRemoveProps(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Selected props will be removed. Continue?", "Attention", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;
            _model.RemoveProps();
        }

        private void onSaveTypesMatch(object sender, RoutedEventArgs e)
        {
            _model.SaveTypesTransformations();
        }

        private void onSetTypesTrans(object sender, RoutedEventArgs e)
        {
            if ( comboTypesTrans.SelectedItem == null)
            {
                MessageBox.Show("Please select Type trans");
                return;
            }

            if (dataGridTemplates.SelectedItems.Count == 0)
            {
                MessageBox.Show("Please select tempates");
                return;
            }

            _model.SetTypeTransToTemplates(dataGridTemplates.SelectedItems.OfType<PropTemplateModel>().ToList(), comboTypesTrans.SelectedItem as TypesTransModel);
        }

        private void onRemoveTemplates(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Selected templates will be removed. Continue?", "Attention", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;
            _model.RemoveTemplates(dataGridTemplates.SelectedItems.OfType<PropTemplateModel>().ToList());
        }

        private void onRemoveTypeTrans(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Selected Types transformations will be removed. Continue?", "Attention", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;
            _model.RemoveTypesTransformations(dataGridTypes.SelectedItems.OfType<TypesTransModel>().ToList());
        }

        private void onLostKeybordFocusDataGrid(object sender, KeyboardFocusChangedEventArgs e)
        {
            var dg = sender as DataGrid;
            if (dg == null)
                return;
            if (dg.IsKeyboardFocusWithin)
                return;
            dg.CommitEdit(DataGridEditingUnit.Row, true);
        }

        private void onSaveData(object sender, RoutedEventArgs e)
        {
            try
            {
                _model.SaveData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);                
            }
        }

        private void onImportData(object sender, RoutedEventArgs e)
        {
            //var dlg = new OpenFileDialog();
            //if (dlg.ShowDialog() != true)
            //    return;
            var raw = Clipboard.GetText();

            try
            {
                _model.ImportData(raw,
                        () => MessageBox.Show("Replace mathched? Yes- replace, No- left current", "Attention", MessageBoxButton.YesNo) == MessageBoxResult.Yes);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void onExportData(object sender, RoutedEventArgs e)
        {
            _model.ExportData();
        }

        private void onRemoveGeneralTemplates(object sender, RoutedEventArgs e)
        {

        }

        private void onGenGeneralTemplate(object sender, RoutedEventArgs e)
        {
            var gtm = dataGridGeneralTemplates.SelectedItem as GeneralTemplateModel;
            if (gtm == null)
            {
                MessageBox.Show("Please select template");
                return;
            }
            _model.GenerateGeneralTemplate(gtm);            
        }        

        private void updateTemplatesMenu()
        {
            if(menuTemplates == null)
                return;
            menuTemplates.Items.Clear();
            var groupedTems = _model.PropTemplates.GroupBy(tem => tem.Category);
            foreach (var grTem in groupedTems)
            {
                var mi = new MenuItem()
                             {
                                 Header = grTem.Key
                             };
                foreach (var tem in grTem)
                {
                    var smi = new MenuItem {Header = tem.Name};
                    smi.DataContext = tem;
                    smi.Click += smi_Click;
                    mi.Items.Add(smi);
                }
                menuTemplates.Items.Add(mi);
            }
        }

        void smi_Click(object sender, RoutedEventArgs e)
        {
            var mi = (MenuItem) sender;
            var tem = (PropTemplateModel)mi.DataContext;
            _model.SetTemplateToProps(tem);
        }

        private void onShowTemplMenu(object sender, RoutedEventArgs e)
        {
            updateTemplatesMenu();
            btnSetTempl.ContextMenu.IsOpen = true;
        }

        private void onEditValues(object sender, RoutedEventArgs e)
        {
            if(dataGridProps.SelectedCells.Count == 0)
                return;
            var dlg = new EnterValueDlg(){ Owner = this };
            if(dlg.ShowDialog() != true)
                return;
            try
            {
                var c = Keyboard.FocusedElement as DataGridCell;
                if (c != null)
                {
                    var ind = c.Column.DisplayIndex;
                    var bnd = (Binding)(((DataGridBoundColumn)c.Column).Binding);
                    var propName = bnd.Path.Path;
                    foreach (var cell in dataGridProps.SelectedCells)
                    {
                        if (cell.Column.DisplayIndex == ind)
                        {
                            cell.Item.GetType().GetProperty(propName).SetValue(cell.Item, dlg.Text, new object[] { });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }                
        }

        private void onEditTemplate(object sender, MouseButtonEventArgs e)
        {
            var tem = ((FrameworkElement)sender).DataContext as PropTemplateModel;
            //var tem = dataGridTemplates.SelectedItem as PropTemplateModel;
            if(tem == null)
                return;

            var dlg = new EnterValueDlg(tem.Text, multiRowText: true){ Owner = this };
            if(dlg.ShowDialog() != true)
                return;
            tem.Text = dlg.Text;
        }

        private void onEditGenTemplate(object sender, MouseButtonEventArgs e)
        {            
            var tem = ((FrameworkElement)sender).DataContext as GeneralTemplateModel;            
            if (tem == null)
                return;

            var dlg = new EnterValueDlg(tem.Template, multiRowText: true) { Owner = this };
            if (dlg.ShowDialog() != true)
                return;
            tem.Template = dlg.Text;
        }            
        
    }
}
